package com.jvm.simulation.hotspot.bytecode;

import com.jvm.simulation.hotspot.ByteUtil;
import com.jvm.simulation.hotspot.CodeAttribute;
import com.jvm.simulation.hotspot.MethodInfo;

public class BytecodeStream extends BaseBytecodeStream {

    byte[] u2 = new byte[2];
    byte[] u4 = new byte[4];

    public BytecodeStream(MethodInfo belongMethod, CodeAttribute belongCode) {
        this.belongMethod = belongMethod;
        this.belongCode = belongCode;
        this.length = belongCode.getCodeLength();
        this.index = 0;
        this.codes = new byte[this.length];
    }

    /**
     * 一次取一字节数据，自动累加
     * @return
     */
    public int getU1Code() {
        if (index < 0 || index >= length) {
            throw new Error("字节码指令的索引超过了最大值");
        }

        return Byte.toUnsignedInt(codes[index++]);
    }

    public short getUnsignedShort() {
        if (index < 0 || index >= length) {
            throw new Error("字节码指令的索引超过了最大值");
        }

        System.arraycopy(codes,index,u2,0,u2.length);

        index += 2;

        return (short) ByteUtil.byteToUnsignedShort(u2);
    }

}